<template>
	<div class="layout-pd">
		<el-card shadow="hover" :header="state.tableData.productInfo?.name">
			<el-row class="flex mt15 mb20" v-if="!state.tableData.edit">
				<div>
					<el-button size="default" type="primary" @click="viewTotalInstance">查看核算信息</el-button>
				</div>
				<div class="flex-end">
					<el-button size="default" type="primary" @click="editProduct">编辑</el-button>
				</div>
			</el-row>
			<el-form ref="tableRulesRef" :model="state.tableData" size="default">
				<el-table ref="tableRef" :data="state.tableData.data" border class="module-table-uncollected">
					<el-table-column v-for="item in state.tableData.header" show-overflow-tooltip :prop="item.prop"
						width="100px;" :label="item.label">
						<template v-slot:header>
							<span class="pl5">{{ item.label }}{{ item.unitCode }}</span>
						</template>
						<template v-slot="scope">
							<el-form-item :prop="`data.${scope.$index}.${item.prop}`">


								<div v-if="item.type === 'input'">
									<el-input v-model="scope.row[item.prop]" />
								</div>
								<div v-else-if="item.type === 'text'">
									<p>{{ scope.row[item.prop] }}</p>
								</div>
								<div v-else-if="item.type === 'operate'">
									<el-button size="small" type="text"
										@click="deleteMaoriInstance(scope.row)">删除</el-button>
								</div>

							</el-form-item>
						</template>
					</el-table-column>

				</el-table>
			</el-form>
			<el-row class="flex mt15" v-if="state.tableData.edit">
				<div class="flex-margin">
					<el-button size="default" type="primary" @click="onOpenAddProductInstance">新增一行</el-button>
					<el-button size="default" type="success" @click="saveProductInstances(tableRulesRef)">保存</el-button>
					<el-button size="default" type="success" @click="calculate">核算</el-button>
				</div>
			</el-row>
		</el-card>
		<maoriProductInstanceDialog ref="maoriProductInstanceDialogRef" @addInstance="addProductInstance" />
		<TotalMaoriProductInstanceDialog ref="TotalMaoriProductInstanceDialogRef" />
	</div>
</template>

<script setup lang="ts" name="maoriProductInstance">
import { reactive, ref, onBeforeMount, defineAsyncComponent } from 'vue';
import { ElMessage } from 'element-plus';
import type { FormInstance } from 'element-plus';
import { useRoute } from 'vue-router';
import { useMaoriApi } from '/@/api/calculate/maori';

// 获取路由数据
const route = useRoute();

// 引入组件
const maoriProductInstanceDialog = defineAsyncComponent(() => import('/@/views/calculate/maori/component/maoriProductInstanceDialog.vue'));
const TotalMaoriProductInstanceDialog = defineAsyncComponent(() => import('/@/views/calculate/maori/component/totalMaoriProductInstanceDialog.vue'));

// 引入 api 请求接口
const maoriApi = useMaoriApi();

const maoriProductInstanceDialogRef = ref();
const TotalMaoriProductInstanceDialogRef = ref();

// 打开新增菜单弹窗
const onOpenAddProductInstance = () => {
	maoriProductInstanceDialogRef.value.openDialog(state.tableData.productInfo);
};

// 打开查看核算信息弹窗
const viewTotalInstance = () => {
	console.log(route.query.id);
	TotalMaoriProductInstanceDialogRef.value.openDialog(route.query.id);
}

// 定义变量内容
const tableRulesRef = ref<FormInstance>();
const tableRef = ref();
const state = reactive<TableRulesState>({
	tableData: {
		data: [],
		header: [
			{ prop: 'variantCodeOneValue', label: '变体1', isRequired: true, type: 'text' },
			{ prop: 'percent', label: '占比', isRequired: true, type: 'text' },
			{ prop: 'purchasePercent', label: '采购占比', isRequired: false, type: 'text' },
			{ prop: 'oceanShipCostPercent', label: '海运费占比', isRequired: false, type: 'text' },
			{ prop: 'landingCostPercent', label: '落地成本占比', isRequired: false, type: 'text' },
			{ prop: 'advertisingPer', label: '广告占比', isRequired: true, type: 'text' },
			{ prop: 'discountPer', label: '折让占比', isRequired: true, type: 'text' },
			{ prop: 'commissionPer', label: '佣金占比', isRequired: true, type: 'text' },
			{ prop: 'marketPercent', label: '营销占比', isRequired: false, type: 'text' },
			{ prop: 'distributionCostPercent', label: '配送占比', isRequired: false, type: 'text' },
			{ prop: 'storageCostPercent', label: '仓储占比', isRequired: false, type: 'text' },
			{ prop: 'refundPer', label: '退款占比', isRequired: true, type: 'text' },
			{ prop: 'operationPercent', label: '运营占比', isRequired: false, type: 'text' },
			{ prop: 'profitMargin', label: '利润率', isRequired: false, type: 'text' },
			{ prop: 'reimbursementRate', label: '回款率', isRequired: false, type: 'text' },
			{ prop: 'price', label: '售价', isRequired: true, type: 'text', isTooltip: true, unitCode: 'USD' },
			{ prop: 'purchaseCost', label: '采购成本', isRequired: true, type: 'text', unitCode: 'CNY' },
			{ prop: 'productLength', label: '产品-长', isRequired: true, type: 'text', unitCode: 'CM' },
			{ prop: 'productWidth', label: '产品-宽', isRequired: true, type: 'text', unitCode: 'CM' },
			{ prop: 'productHeight', label: '产品-高', isRequired: true, type: 'text', unitCode: 'CM' },
			{ prop: 'outerCartonPackCount', label: '装箱量', isRequired: true, type: 'text' },
			{ prop: 'packetLength', label: '装箱-长', isRequired: true, type: 'text', unitCode: 'CM' },
			{ prop: 'packetWidth', label: '装箱-宽', isRequired: true, type: 'text', unitCode: 'CM' },
			{ prop: 'packetHeight', label: '装箱-高', isRequired: true, type: 'text', unitCode: 'CM' },
			{ prop: 'productWeight', label: '单个产品净重', isRequired: true, type: 'text', unitCode: 'KG' },
			{ prop: 'packageWeight', label: '单个产品包装重', isRequired: true, type: 'text', unitCode: 'KG' },
			{ prop: 'packetTrueWeight', label: '整箱实重', isRequired: true, type: 'text', unitCode: 'KG' },
			{ prop: 'volumeWeight', label: '整箱体积重', isRequired: false, type: 'text', unitCode: 'KG' },
			{ prop: 'distributionCost', label: '配送费', isRequired: true, type: 'text', unitCode: 'USD' },
			{ prop: 'storageCost', label: '仓储费', isRequired: false, type: 'text', unitCode: 'USD' },
			{ prop: 'oceanShipCost', label: '海运费用', isRequired: false, type: 'text', unitCode: 'CNY' },
		],
		edit: false,
	},
});

// 打开编辑页面
const editProduct = () => {
	state.tableData.edit = true;
	for (const headerItem of state.tableData.header) {
		if (headerItem.isRequired) {
			headerItem.type = 'input';
		}
	}
	const operateHeader = { prop: 'operate', label: '操作', isRequired: false, type: 'operate' };
	state.tableData.header.push(operateHeader);
}

// 获取项目信息
async function initProductData() {
	const productData = await maoriApi.productDetail(route.query);
	if (productData.data.length <= 0)
		return Promise.resolve(true);
	const productDetail: CostingProduct = productData.data;
	state.tableData.productInfo = productDetail;

	const priceUnitCode = productDetail.priceUnit;
	const weightUnit = productDetail.weightUnit;
	const productUnit = productDetail.productUnit;

	for (const headerItem of state.tableData.header) {
		if (headerItem.prop == 'price' || headerItem.prop == 'distributionCost' || headerItem.prop == 'storageCost') {
			headerItem.unitCode = priceUnitCode;
		} else if (headerItem.prop == 'productWeight' || headerItem.prop == 'packageWeight' || headerItem.prop == 'packetTrueWeight' || headerItem.prop == 'volumeWeight') {
			headerItem.unitCode = weightUnit;
		} else if (headerItem.prop == 'productLength' || headerItem.prop == 'productWidth' || headerItem.prop == 'productHeight'
			|| headerItem.prop == 'packetLength' || headerItem.prop == 'packetWidth' || headerItem.prop == 'packetHeight'
		) {
			headerItem.unitCode = productUnit;
		} else if (headerItem.prop == 'variantCodeOneValue' && '' != productDetail.variantCodeOne) {
			headerItem.label = productDetail.variantCodeOne;
		}
	}
	if ('' != productDetail.variantCodeTwo) {
		const variantCodeTwo = { prop: 'variantCodeTwoValue', width: '', label: productDetail.variantCodeTwo, isRequired: false, type: 'text' };
		state.tableData.header.splice(1, 0, variantCodeTwo);
	}

}

// 初始化项目核算细节信息
async function initProductInstanceData() {
	state.tableData.header = state.tableData.header.filter(item => item.type != 'operate');
	await flashProductInstanceList();
	state.tableData.edit = false;
	for (const headerItem of state.tableData.header) {
		headerItem.type = 'text';
	}
}

// 刷新数据
async function flashProductInstanceList() {
	const productInstanceData = await maoriApi.productInstanceList(route.query);
	if (productInstanceData.data == null)
		return Promise.resolve(true);
	const productInstanceList: CostingProductInstance[] = productInstanceData.data.rows;
	state.tableData.data = [];
	for (const instance of productInstanceList) {
		state.tableData.data.push(instance);
	}
}

//保存
async function saveProductInstances(formEl: FormInstance | undefined) {
	if (state.tableData.data.length <= 0) return ElMessage.warning('请先点击增加一行');
	if (!formEl) return;
	const param = {
		costingProductId: state.tableData.productInfo?.id,
		instanceList: state.tableData.data,
	}
	await maoriApi.saveProductInstances(param);
	initProductInstanceData();
};

// 删除
async function deleteMaoriInstance(row: any) {
	const param = {
		costingProductInstanceId: row.id,
	}
	await maoriApi.deleteProductInstance(param);
	state.tableData.data = state.tableData.data.filter(item => item.id != row.id);
}

//核算
async function calculate() {
	const param = {
		costingProductId: state.tableData.productInfo?.id,
		instanceList: state.tableData.data,
	}
	await maoriApi.calculateProductInstances(param);
	initProductInstanceData();
}

//添加一行
async function addProductInstance(instanceInfo: any) {
	const maoriProductId = route.query.id;
	const param = {
		"costingProductId": maoriProductId,
		...instanceInfo,
	}
	const result = await maoriApi.addProductInstances(param);
	if (result.data == null)
		return Promise.resolve(true);
	const newInstance: CostingProductInstance = result.data;
	state.tableData.data.push(newInstance);
}

// 页面加载前
onBeforeMount(() => {
	initProductData();

	initProductInstanceData();
});
</script>

<style scoped>
.flex-end {
	margin-left: auto;
	/* 将内容推到右侧 */
}
</style>
